﻿<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Net;

public class Thumbnail : IHttpHandler {
    private Regex _nameValidationExpression = new Regex(@"[^\w/]");
    private int _thumbnailSize;
    private string RequestImage;
    
    
    public void ProcessRequest(HttpContext context) 
    {
        GetParameters();
        
        //string photoName = context.Request.QueryString["p"];
        //if (_nameValidationExpression.IsMatch(photoName)) {
        //    throw new HttpException(404, "Invalid photo name.");
        //} 
        string photoName=RequestImage.Split('/')[RequestImage.Split('/').Length-1];
        string cachePath = Path.Combine(HttpRuntime.CodegenDir, photoName.Remove(photoName.Length - 4) +"^"+ _thumbnailSize.ToString()+ ".square.png");
        //if (File.Exists(cachePath)&&!RequestImage.Contains("http"))
        //{
        //    OutputCacheResponse(context, File.GetLastWriteTime(cachePath));
        //    context.Response.WriteFile(cachePath);
        //    return;
        //}
        
        string photoPath = context.Server.MapPath("~/gallery/" + photoName);

        StreamReader sr = null;
        HttpWebResponse webResponseObject = null;
        HttpWebRequest webRequestObject = null;
        Bitmap photo;
        try
        {
            webRequestObject = (HttpWebRequest)WebRequest.Create(RequestImage);
            webRequestObject.Method = "GET";

            webResponseObject = (HttpWebResponse)webRequestObject.GetResponse();
            sr = new StreamReader(webResponseObject.GetResponseStream());
            
            photo = new Bitmap(sr.BaseStream);
        }
        catch (ArgumentException) {
            throw new HttpException(404, "Photo not found.");
        }
        finally
        {
            try
            {
                sr.Close();
                webResponseObject.Close();
                webRequestObject.Abort();
            }
            catch { }
        }
        context.Response.ContentType = "image/png";
        int width, height;
        if (photo.Width > photo.Height) {
            width = _thumbnailSize * photo.Width / photo.Height;
            height = _thumbnailSize;
        }
        else {
            width = _thumbnailSize;
            height = _thumbnailSize * photo.Height / photo.Width;
        }
        Bitmap target = new Bitmap(_thumbnailSize, _thumbnailSize);
        using (Graphics graphics = Graphics.FromImage(target)) {
            graphics.CompositingQuality = CompositingQuality.HighSpeed;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.DrawImage(photo, (_thumbnailSize - width) / 2, (_thumbnailSize - height) / 2, width, height);
            using (MemoryStream memoryStream = new MemoryStream()) {
                target.Save(memoryStream, ImageFormat.Png);
                //OutputCacheResponse(context, File.GetLastWriteTime(cachePath));
            //    if (!RequestImage.Contains("http"))
            //    {
            //        using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew))
            //        {
            //            memoryStream.WriteTo(diskCacheStream);
            //        }

            //    }
                memoryStream.WriteTo(context.Response.OutputStream);
            }
        }
    }
    
    private void GetParameters()
    {
        RequestImage = HttpContext.Current.Request.QueryString["Img"];
        _thumbnailSize = Convert.ToInt32((HttpContext.Current.Request.QueryString["size"]));
    }

    private static void OutputCacheResponse(HttpContext context, DateTime lastModified)
    {

        HttpCachePolicy cachePolicy = context.Response.Cache;
        cachePolicy.SetCacheability(HttpCacheability.Public);
        cachePolicy.VaryByParams["Img"] = true;
        cachePolicy.SetOmitVaryStar(true);
        cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(7));
        cachePolicy.SetValidUntilExpires(true);
        cachePolicy.SetLastModified(lastModified);

    }
 
    public bool IsReusable {
        get {
            return true;
        }
    }
}